package com.binance.autojob.utils;

import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.util.CollectionUtils;

import com.binance.autojob.annotation.MyScheduledJob;


public class JobClassInteruptor implements ApplicationListener<ContextRefreshedEvent> {
    private static Logger logger = LoggerFactory.getLogger(JobClassInteruptor.class);

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        if (event == null) {
            logger.error("ContextRefreshedEvent为空。");
            return;
        }
        if (event.getApplicationContext() == null) {
            logger.error("ApplicationContext为空。");
            return;
        }
        Map<String, Object> beans = event.getApplicationContext().getBeansWithAnnotation(MyScheduledJob.class);
        if (!CollectionUtils.isEmpty(beans)) {
            for (Entry<String, Object> entity : beans.entrySet()) {
                Object bean = entity.getValue();//
                Method[] methods = bean.getClass().getMethods();
                MyScheduledJob ann = bean.getClass().getAnnotation(MyScheduledJob.class);
                for (Method method : methods) {
                    // 排除来自Object的公共方法
                    if (!Object.class.getName().equals(method.getDeclaringClass().getName())) {
                        if (method.getAnnotation(MyScheduledJob.class) == null) {// 方法上有注释的由拦截器处理
                            ExecutorExt.regist(bean, method, ann);
                        }
                    }
                }
            }
        }
    }
}


